package ru.task;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import static java.time.temporal.ChronoUnit.MINUTES;

public class Main {

	public static void main(String args[]) {
		JsonSimpleParser parser = new JsonSimpleParser();
		Root root = parser.parse();

		Map<String, Long> minTime = new HashMap<>();
		List<Ticket> listTicket = root.getTickets();
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yy H:mm");

		// get betwen Valdivostok - Tel-aviv
		List<Integer> prices = new ArrayList<>();
		for(Ticket ticket : listTicket) {
			String originName = ticket.getOriginName();
			String destinationName = ticket.getDestinationName();
			if (originName.equals("Владивосток") && destinationName.equals("Тель-Авив")){

				LocalDateTime timeDeparture = LocalDateTime.parse((ticket.getDepartureDate() + " " + ticket.getDepartureTime()), dtf);
				LocalDateTime timeArrival = LocalDateTime.parse((ticket.getArrivalDate() + " " + ticket.getArrivalTime()), dtf);
				long until = timeDeparture.until(timeArrival, MINUTES);
				if (minTime.get(ticket.getCarrier()) == null) {
					minTime.put(ticket.getCarrier(), until);
				} else {
					if (minTime.get(ticket.getCarrier()) > until) {
						minTime.put(ticket.getCarrier(), until);
					}
				}

				prices.add(ticket.getPrice());
			}
		}

		for(Map.Entry<String, Long> item : minTime.entrySet()) {
			Integer hours = item.getValue().intValue() / 60;
			Integer minutes = item.getValue().intValue() % 60;
			System.out.printf("Carrier: %s Until: %d HH:MM = %d:%d\n", item.getKey(), 
				item.getValue(), hours, minutes);
		}

		Collections.sort(prices);
		double averagePrice = 0.0;
		int allSum = 0;
		for(Integer num : prices) {
			allSum += num;
			System.out.println(num);
		}
		averagePrice = (double)allSum / prices.size();
		System.out.println("Average value = " + averagePrice);

		double medianPrice = 0.0;
		int num1 = 0;
		int num2 = 0;
		int length = prices.size();
		if ((length % 2) == 0) {
			num2 = length / 2;
			num1 = num2 - 1 ;
			medianPrice = ((double)prices.get(num1) + (double)prices.get(num2)) / 2.0;
		} else {
			num1 = length / 2;
			medianPrice = (double)prices.get(num1);
		}
		System.out.println("Median = " + medianPrice);
		double differencePrice = averagePrice - medianPrice;
		System.out.println("Difference = " + differencePrice);
	}
}
